import React, { FC } from "react"
import classNames from "classnames"
import useGetComponentInfo from "../../../../hooks/useGetComponentInfo"
import { getComponentConfigByType } from "../../../../components/QuestionComponents"
import styles from "./ComponnetList.module.scss"

type PropsType = {
    selectedComponentId: string
    setSelectedComponentId: (id: string) => void

    setSelectedComponentType: (type: string) => void
}

const ComponentList: FC<PropsType> = (props: PropsType) => {
    const { selectedComponentId, setSelectedComponentId, setSelectedComponentType } = props
    const { componentList } = useGetComponentInfo()

    return (
        <div className={styles.container}>
            {/* filter 如果为true则被保留下来 */}
            {/* 过滤隐藏的组件 */}
            {componentList
                .filter(c => !c.isHidden)
                .map(c => {
                    const { fe_id, props, type } = c

                    const componentConfig = getComponentConfigByType(type)
                    if (componentConfig == null) return null

                    const { Component } = componentConfig

                    // 拼接class name
                    const wrapperDefaultClassName = styles["component-wrapper"]
                    const selectedClassName = styles.selected
                    const wrapperClassName = classNames({
                        [wrapperDefaultClassName]: true,
                        [selectedClassName]: fe_id === selectedComponentId // 是否选中
                    })

                    return (
                        <div
                            className={wrapperClassName}
                            key={fe_id}
                            onClick={() => {
                                setSelectedComponentId(fe_id)
                                setSelectedComponentType(type)
                            }}
                        >
                            <div className={styles.component}>
                                <Component {...props}></Component>
                            </div>
                        </div>
                    )
                })}
        </div>
    )
}

export default ComponentList
